const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');

// 确保日志目录存在
const logsDir = path.join(__dirname, '../log');
if (!fs.existsSync(logsDir)) {
  fs.mkdirSync(logsDir, { recursive: true });
}

const logFilePath = path.join(logsDir, 'api.log');

// 读取日志文件
const readLogFile = () => {
    try {
      const logData = fs.readFileSync(logFilePath, 'utf8');
      const logLines = logData.trim().split('\n');
      const logObjects = logLines.map(line => {
        const parts = line.split(' - ');
        const timestamp = parts[0];
        const logEntry = parts[1];
        const [method, url, requestBody, responseStatus, responseBody, error] = logEntry.split(', ');
        return {
          timestamp,
          method: method.split(': ')[1],
          url: url.split(': ')[1],
          requestBody: requestBody ? requestBody.split(': ')[1] : '',
          responseStatus: parseInt(responseStatus.split(': ')[1]),
          responseBody: responseBody ? responseBody.split(': ')[1] : '',
          error: error ? error.split(': ')[1] : ''
        };
      }).sort((a, b) => {
        // 将字符串转化为日期对象进行比较
        return new Date(b.timestamp) - new Date(a.timestamp);
      });
      return logObjects;
    } catch (err) {
      console.error('Error reading log file:', err);
      return [];
    }
  };

// 创建一个新路由来获取日志数据
router.get('/logs', (req, res) => {
  const logData = readLogFile();
  res.setHeader('Content-Type', 'text/plain');
  res.send(logData);
});
router.get('/view', (req, res) => {
    const logData = readLogFile(); // 使用前面定义的 readLogFile 函数
  res.render('logs', { logs: logData }); // 渲染logs.pug模板，传入日志数据
  });
module.exports = router;